#pragma once

#include <iostream>
#include <unordered_map>
#include <functional>
#include <ctime>
#include <sys/types.h>
#include <unistd.h>

using task_t = std::function<void()>;

class TaskManger
{
public:
    TaskManger()
    {
        srand(time(nullptr));
        tasks.push_back([](){ 
            std::cout << "sub process[ " << getpid() << " ] 执行访问数据库任务\n"<< std::endl; 
        });
        tasks.push_back([](){ 
            std::cout << "sub process[ " << getpid() << " ] 执行URL解析\n"<< std::endl; 
        });
        tasks.push_back([](){
            std::cout << "sub process[ " << getpid() << " ] 执行加密任务\n"<< std::endl; 
        });
        tasks.push_back([](){ 
            std::cout << "sub process[ " << getpid() << " ] 执行数据库持久化任务\n"<< std::endl; 
        });
    }

    int SelectTask()
    {
        return rand() % tasks.size();
    }

    void Excute(unsigned long number)
    {
        if(number > tasks.size() || number < 0)
            return;

        tasks[number]();
    }

    ~TaskManger()
    {}

private:
    std::vector<task_t> tasks;
};

TaskManger tm;

void Worker() //获取并执行任务
{
    while(true)
    {
        int cmd = 0;  //任务在vector中的下标
        int n = ::read(0, &cmd, sizeof(cmd));
        if(n == sizeof(cmd))
        {
            tm.Excute(cmd);
        }
        else if(n == 0) //写端关闭，子进程退出
        {
            //不需要关闭子进程的文件描述符，子进程退出后会自动关闭
            std::cout<< "pid: " <<getpid() << " quit..." << std::endl;
            break;
        }
        else
        {
            //....其他操作
        }
    }
}
